/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package aiaudio.processing.network.manager;

import aiaudio.processing.base.mapreduce.CoordinateDoubleValueKey;
import aiaudio.Application;
import aiaudio.database.tables.RatingsMatrixTable;
import java.io.IOException;
import java.util.Vector;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.mapreduce.TableReducer;
import org.apache.hadoop.hbase.util.Bytes;

/**
 *
 * @author nastya
 */
public class CollectNecessaryValuesReducer extends TableReducer<ImmutableBytesWritable, CoordinateDoubleValueKey, ImmutableBytesWritable> {

    public static final String INCLUDE_ARTISTS = "includeArtists";
    public static final String RATING_MATRIX_NAME = "ratingMatrix";
    Result defaultVoting;
    Vector<String> includedArtists;

    @Override
    protected void setup(Context context) throws IOException, InterruptedException {
        super.setup(context);
        String ratingMatrixName = context.getConfiguration().get(RATING_MATRIX_NAME);
        defaultVoting = setupDefaultVoting(ratingMatrixName);
        String[] includeArtists = context.getConfiguration().getStrings(INCLUDE_ARTISTS);
        includedArtists = new Vector<String>();
        for (String string : includeArtists) {
            includedArtists.add(string);
        }
    }

    @Override
    protected void reduce(ImmutableBytesWritable key, Iterable<CoordinateDoubleValueKey> values, Context context) throws IOException, InterruptedException {

        Put put = new Put(key.get());
        Vector<String> notAdded = new Vector<String>(includedArtists);
        for (CoordinateDoubleValueKey coordinateDoubleValueKey : values) {
            byte[] coord = coordinateDoubleValueKey.getCoordinate();
            String coordinate = Bytes.toString(coord);
            if (notAdded.contains(coordinate)) {
                notAdded.remove(coordinate);
                RatingsMatrixTable.addUserRating(put, coord, coordinateDoubleValueKey.getValue());
            }
        }

        double value = RatingsMatrixTable.getValue(defaultVoting, key.get());
        for (String na : notAdded) {
            byte[] art = Bytes.toBytes(na);
            RatingsMatrixTable.addUserRating(put, art, value);

        }
        context.write(new ImmutableBytesWritable(key), put);

    }

    private Result setupDefaultVoting(String ratingMatrixName) throws IOException {
        HTable table = Application.database().getByName(ratingMatrixName).getTable();
        return RatingsMatrixTable.getDefaultRatings(table);
    }
}
